﻿Imports System.IO.File
''Imports Twitterizer
Imports TwitterVB2

Public Class frmPIN
    Public tw As New TwitterAPI
    Dim consumer As String = "3rZoMe2v9ZDq5T1JoyVzyw"
    Dim consumersecret As String = "Za0raOo0mDs0xqgmmGxS1YI7hxUdoPmBnGtfFVHBek"
    Public oauthtoken As String
    Public oauthtokensecret As String
    Dim strPassword As String
    Public strUserName As String
    Dim oFile As System.IO.File
    Dim oWrite As System.IO.StreamWriter
    Dim strURL As String


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim isValid As Boolean = tw.ValidatePIN(TextBox1.Text)
        If isValid = True Then

            Try

                oauthtoken = tw.OAuth_Token
                oauthtokensecret = tw.OAuth_TokenSecret

                My.Settings.LastUsername = strUserName

                'My.Settings.lstUsernames.Add(strUserName)
                'My.Settings.lstToken.Add(oauthtoken)
                'My.Settings.lstTokenSecret.Add(oauthtokensecret)
                My.Settings.m_strToken = oauthtoken
                My.Settings.m_strTokenSecret = oauthtokensecret
                My.Settings.Save()



                '         getcode()
                'frmMain_2.ToolStripStatusLabel2.Text = tw.AccountInformation.FollowersCount
                'frmMain_2.ToolStripStatusLabel4.Text = tw.AccountInformation.FriendsCount
                'frmMain_2.ToolStripStatusLabel6.Text = tw.AccountInformation.StatusesCount

                'frmMain_2.TextBox8.Text = tw.AccountInformation.ScreenName
                'frmMain_2.Text = "Smart Promoter - " & tw.AccountInformation.ScreenName
                'For Each entry In tw.HomeTimeline()
                '     ListBox1.Items.Add(entry.Text.ToString)

                'frmMain_2.ListView1.BeginUpdate()
                'n = frmMain_2.ListView1.Items.Add(entry.User.ScreenName.ToString)
                'n.SubItems.Add(entry.Text.ToString)
                'n.SubItems.Add(entry.CreatedAtLocalTime.ToString)
                'n.SubItems.Add(entry.ID.ToString)

                'n.SubItems.Add(entry.CreatedAt.ToString)

                'frmMain_2.ListView1.Refresh()
                'frmMain_2.ListView1.EndUpdate()

                'Next

                '         My.Computer.Network.DownloadFile(tw.AccountInformation.ProfileImageUrl, My.Application.Info.DirectoryPath + "/profilepic.png", "", "", False, 999999, True)
                '         Form1.PictureBox1.Image = Image.FromFile(My.Application.Info.DirectoryPath + "/profilepic.png")
                'frmMain_2.PictureBox1.ImageLocation = tw.AccountInformation.ProfileImageUrl

                frmMain.oauthtoken = tw.OAuth_Token
                frmMain.oauthtokensecret = tw.OAuth_TokenSecret

                tw.AuthenticateWith(consumer, consumersecret, My.Settings.m_strToken, My.Settings.m_strTokenSecret)

                IO.File.Delete(Application.StartupPath & "\" & tw.AccountInformation.ScreenName.ToLower & "_OAuthtk.dat")
                IO.File.Delete(Application.StartupPath & "\" & tw.AccountInformation.ScreenName.ToLower & "_OAuthtkST.dat")

                oWrite = IO.File.CreateText(Application.StartupPath & "\" & tw.AccountInformation.ScreenName.ToLower & "_OAuthtk.dat")
                oWrite.WriteLine(tw.OAuth_Token)
                oWrite.Close()


                oWrite = IO.File.CreateText(Application.StartupPath & "\" & tw.AccountInformation.ScreenName.ToLower & "_OAuthtkST.dat")
                oWrite.WriteLine(tw.OAuth_TokenSecret)
                oWrite.Close()

                'frmMain.oauthtokens.SetValue(tw.OAuth_Token, 0)
                'frmMain.oauthtokens.SetValue(tw.OAuth_TokenSecret, 1)
                frmMain.Show()
                Me.Hide()
            Catch ex As Exception

                MsgBox("There was an error logging in. Please try again or a different username.")
                Me.Hide()
                frmLogin.Show()
                Me.Dispose()

            End Try
            '   Else
            '        MsgBox("WRONG CODE!")

        End If


    End Sub

    Function GetLinkURL() As String
        Return tw.GetAuthorizationLink(consumer, consumersecret)

    End Function

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        strURL = GetLinkURL()
        web.Navigate(strURL)

    End Sub

    Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyCode = Keys.Enter Then
            Button1.PerformClick()
        End If
    End Sub

    Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click
        TextBox1.Copy()
    End Sub

    Private Sub ToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem3.Click
        TextBox1.Paste()
    End Sub

    Private Sub Form3_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        frmLogin.Dispose()
        frmMain.Dispose()
        'frmMain_2.Dispose()
        End
    End Sub

    Private Sub frmPIN_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        strURL = GetLinkURL()
        On Error Resume Next

        '-- Obtain a request token
        'Dim requestToken As OAuthTokenResponse = OAuthUtility.GetRequestToken(consumer, consumersecret, OAuthUtility.BuildAuthorizationUri(requestToken.Token).ToString)

        '-- Direct or instruct the user to the following address:
        'Dim authorizationUri As Uri = OAuthUtility.BuildAuthorizationUri(requestToken.Token)

        web.Navigate(strURL)

    End Sub

    Private Sub web_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles web.DocumentCompleted

        'Dim text = (From xItem In web.Document.GetElementsByTagName("code").OfType(Of HtmlElement)()).ToString

        If (web.DocumentText.Contains("You've granted access to")) Then
            'If InStr("Next, return to SmartPromoter and enter this PIN to complete the authorization process:", web.Document.GetElementById("code-desc").InnerText) Then

            Dim text = web.Document.GetElementsByTagName("code")(0).InnerText

            'web.DocumentText.ElementAt(web.Document.GetElementById("oauth_pin"))

            web.Visible = False
            lblAuth.Visible = True
            TextBox1.Text = text
            tmrAuth.Enabled = True
            'tmrAuth.Start()

            'End If
        End If

    End Sub

    Private Sub tmrAuth_Tick(sender As System.Object, e As System.EventArgs) Handles tmrAuth.Tick

        Button1.PerformClick()
        tmrAuth.Enabled = False

    End Sub
End Class